import { UUID } from "uuidjs";

/**
 * 启动应用时候注入全局信息
 */
export default defineNuxtPlugin(async (nuxtApp) => {
  const route = useRoute();

  const LOCAL_KEY = "user_id";
  const LOCAL_UUID_KEY = "user_uuid";
  const localUserId = localStorage.getItem(LOCAL_KEY);
  const localUUId = localStorage.getItem(LOCAL_UUID_KEY);

  let userId = localUserId;

  const uuid = route.query.uuid || localUUId || UUID.generate();
  localStorage.setItem(LOCAL_UUID_KEY, uuid.toString());

  if (!localUserId || localUserId === "undefined" || localUserId === "null") {
    const loadingToast = showLoadingToast({ duration: 0 });

    try {
      const res = await useHttp<{
        accessToken: string;
        hashId: string;
        isNew: string;
        userId: string;
      }>({
        url: `/user/normal_login`,
        method: "POST",
        data: { uuid },
      });

      localStorage.setItem(LOCAL_KEY, res.userId);
      userId = res.userId;
    } catch (e) {
      showDialog({
        title: "NET ERROR",
        message: "Please refresh the page and try again",
        confirmButtonText: "CONFIRM",
      }).then(() => {
        window.location.reload();
      });
    }

    loadingToast.close();
  }

  // 将数据注入到全局上下文
  nuxtApp.provide("globalData", { userId: userId, uuid: uuid });
});
